<?php

defined( '_JEXEC' ) or die( 'Restricted access' );

jimport( 'joomla.application.component.controller' );

class AuctionControllerDefault extends JController
{
	function __construct( $default = array())
	{
		parent::__construct( $default );
		$this->registerTask( 'add', 'edit' );
		$this->registerTask( 'apply',	'save' );
	}

	function display() 
	{
	   parent::display();
	}
	
	
		/**
	 * display the edit form
	 * @return void
	 */
	function edit()
	{
		JRequest::setVar( 'view', 'edit' );
		JRequest::setVar( 'layout', 'default'  );
		JRequest::setVar('hidemainmenu', 1);
		parent::display();

	}

	/**
	 * save a record (and redirect to main page)
	 * @return void
	 */
	function save()
	{
		$model = $this->getModel('edit');
		
		if ($model->store()) {
			$msg = JText::_( 'Auction Saved' );
		} else {
			$msg = JText::_( 'Error Saving Auction' );
		}
	
		$task = JRequest::getCmd( 'task' );
	
		$array	= JRequest::getVar('cid', 0, '', 'array');
		$cid = (int)$array[0];
		
		switch ($task)
		{
			case 'apply':
				$link = 'index.php?option=com_auction&task=edit&cid[]='. $cid ;
				break;

			case 'save':
			default:
				$link = 'index.php?option=com_auction';
				break;
		}

		$this->setRedirect($link, $msg);
	}

	/**
	 * remove record(s)
	 * @return void
	 */
	function remove()
	{
		$model = $this->getModel('edit');
		if(!$model->delete()) {
			$msg = JText::_( 'Error, cannot deleted' );
		} else {
			$msg = JText::_( 'Auction Deleted!' );
		}
		$this->setRedirect( 'index.php?option=com_auction', $msg );
	}

	/**
	 * cancel editing a record
	 * @return void
	 */
	function cancel()
	{
		$msg = JText::_( 'Operation Cancelled' );
		$this->setRedirect( 'index.php?option=com_auction', $msg );
	}
	
	function publish() {
		$model = $this->getModel('edit');
		$model->publish(1);
		$this->setRedirect( 'index.php?option=com_auction', $msg );
	}
	
	function unpublish() {
		$model = $this->getModel('edit');
		$model->publish(0);
		$this->setRedirect( 'index.php?option=com_auction', $msg );
	}
	
	function show() {
		$model = $this->getModel('edit');
		$model->show(1);
		$this->setRedirect( 'index.php?option=com_auction', $msg );
	}
	
	function unshow() {
		$model = $this->getModel('edit');
		$model->show(0);
		$this->setRedirect( 'index.php?option=com_auction', $msg );
	}
	
	function sendMail(){
		$db = JFactory::getDBO();
		$query = "SELECT product_id FROM #__auction WHERE closed = 0";
		$db->setQuery($query);
		$proArr = $db->loadResultArray();
		
		$query = "SELECT id, like_products FROM #__users WHERE post = 0 AND gid = 18";
		$db->setQuery($query);
		$userArr = $db->loadObjectList();
		
		$i = 0;
		foreach($userArr as $user){
			if($user->like_products){
				$likeProArr = explode(',', $user->like_products);
				$sendProArr = array_intersect($proArr, $likeProArr);
				if($sendProArr){
					$sendList[$i]->user_id = $user->id;
					$sendList[$i]->products = $sendProArr;
				}
				$i++;
			}
		}
		
		foreach($sendList as $send){
			$this->send($send->user_id, $send->products);
		}
		
		$this->setRedirect( 'index.php?option=com_auction', "Email is sent" );
	}
	
	function send($user_id, $products){
		//Send Email
		$db = JFactory::getDBO();
		$db->setQuery("SELECT email FROM #__users WHERE id = ".$user_id);
		$to = $db->loadResult();
		
		$strCar = implode(',', $products);
		$db->setQuery("SELECT model FROM #__pr_product WHERE id IN (".$strCar.")");
		$carArr = $db->loadResultArray();
		
		$config = new JConfig(); //print_r($to);exit;
		$from = $config->mailfrom; // email admin
		$subject = $config->fromname;
		$body = "Biler, der interesserer dig flyttet ud af auktionen:";
		foreach($carArr as $model){
			$body .= "<br /> - ".$model;
		}

		$message =& JFactory::getMailer();
		$message->IsHTML(true);
		$message->addRecipient($to); //nguoi nhan mail
		$message->setSubject($subject); // tieu de
		$message->setBody($body); // noi dung mail
		$sender = array( $from, $config->sitename ); // email he thong
		$message->setSender($sender);
		$sent = $message->send();
	}
	
	function refundMoney(){
		require_once(JPATH_BASE.DS.'components'.DS.'com_auction'.DS.'class.quickpay.php');

		$amount = 3500*100;				
		$msgtype = 'refund';
		$merchant = '33163916';
		
		$db = JFactory::getDBO();
		$query = "SELECT p.id, p.transaction, p.user_id FROM #__users_pay as p LEFT JOIN #__users as u ON p.user_id = u.id WHERE p.refund = 0 AND p.success = 1 AND u.checkout_status = 1 AND u.buy = 0";
		$db->setQuery($query);
		$transactions = $db->loadObjectList();
		
		foreach($transactions as $tran){
			$data = array('protocol' => 5,'msgtype' => $msgtype, 'merchant' => $merchant, 'amount' => $amount, 'transaction' => $tran->transaction, 'md5check' => '1LDG6h84687QKv24Wcabg9Sr4H2B17yz3pC3IJA56s1ZVw69t7mjU8kdTP7E5q49');
			$quickPay = new QuickPay($data);
			//print_r($quickPay);exit;
			$qr = $quickPay->commit();
			//print_r($qr);exit;
			if($qr['qpstat']=="000"){
				$query = "UPDATE #__users_pay SET refund = 1 WHERE id = ".$tran->id;
				$db->setQuery($query);
				$db->query();
				
				$query = "UPDATE #__users SET buy = 0, checkout_status = 0, transaction = '' WHERE id = ".$tran->user_id;
				$db->setQuery($query);
				$db->query();
				
				$this->setRedirect( 'index.php?option=com_auction', "Refunded" );
			} else {
				echo '<script>alert("'.$qr['qpstat'].'");window.history.go(-1);</script>';
				exit();
			}
		}
	}
	
	function saveDate(){
		$db = JFactory::getDBO();
		$date = JRequest::getVar('date');
		$query = "UPDATE #__auction_date SET auction_date = '".$date."' WHERE id = 1";
		$db->setQuery($query);
		$db->query();

		$query = "SELECT a.id FROM #__auction a INNER JOIN #__pr_product p ON a.product_id = p.id WHERE p.bought = 0 AND a.closed = 0";
		$db->setQuery($query);
		$pros = $db->loadResultArray();
		$strPros = implode(',', $pros);
		$query = "UPDATE #__auction SET auction_date = '".$date."' WHERE id IN (".$strPros.")";
		$db->setQuery($query);
		$db->query();
		$this->setRedirect( 'index.php?option=com_auction', "Saved the auction date" );		
	}
	
	function saveAuctionStatus(){
		$db = JFactory::getDBO();
		$status = JRequest::getVar('status');
		$query = "UPDATE #__auction_date SET auction_date = '".$status."' WHERE id = 2";
		$db->setQuery($query);
		$db->query();
		if($status) $msg = "The auction is published"; else $msg = "The auction is unpublished";

		$this->setRedirect( 'index.php?option=com_auction', $msg );		
	}
} 